import React from 'react'
import { Button, Table, notification } from 'antd'
import axios from 'axios'

export default function NewsPublish(props) {
    const btnList = ["", "发布", "下线", "删除"]

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`} >{title}</a>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => {
                return category.title
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button shape="primary"
                        onClick={() => { handleAudit(item, props.publishState) }}
                        danger={props.publishState === 3 ? true : false}>{btnList[props.publishState]}</Button>
                </div>
            }
        },
    ];

    const handleAudit = (item, type) => {
        if (type === 1) {
            axios.patch(`/news/${item.id}`, { publishState: 2, publishTime: Date.now() }).then(res => {
                props.setdataSource(props.dataSource.filter(data => data.id !== item.id))
                notification.info({
                    message: `通知`,
                    description: `您可以到【发布管理/已发布】中查看发布的新闻!`,
                    placement: "bottomRight"
                })
            })
        } else if (type == 2) {
            axios.patch(`/news/${item.id}`, { publishState: 3 }).then(res => {
                props.setdataSource(props.dataSource.filter(data => data.id !== item.id))
                notification.info({
                    message: `通知`,
                    description: `您可以到【发布管理/已下线】中查看下线的新闻!`,
                    placement: "bottomRight"
                })
            })
        } else {
            axios.delete(`/news/${item.id}`).then(res => {
                props.setdataSource(props.dataSource.filter(data => data.id !== item.id))
                notification.info({
                    message: `通知`,
                    description: `您删除了1条新闻!`,
                    placement: "bottomRight"
                })
            })
        }
    };

    return (
        <div>
            <Table dataSource={props.dataSource} columns={columns}
                pagination={{
                    pageSize: 5
                }}
                rowKey={(item) => item.id}
            />
        </div>
    )
}

